<template>
  <a-form-model
    :model="formInline"
    :rules="rules"
    ref="form"
    @submit.native.prevent="handleSubmit"
  >
    <a-form-model-item ref="username" prop="username">
      <a-input
        v-model="formInline.username"
        placeholder="邮箱/手机号 （国际号码加区号）"
        style="width: 27rem"
      >
      </a-input>
    </a-form-model-item>
    <a-form-model-item ref="password" prop="password">
      <a-input
        v-model="formInline.password"
        type="password"
        placeholder="请输入密码"
        style="width: 27rem"
      >
      </a-input>
    </a-form-model-item>
    <a-form-model-item
      v-if="type === '注册'"
      ref="repassword"
      prop="repassword"
    >
      <a-input
        v-model="formInline.repassword"
        type="password"
        placeholder="请再次输入密码"
        style="width: 27rem"
      >
      </a-input>
    </a-form-model-item>
    <a-form-model-item>
      <a-button type="primary" html-type="submit" style="width: 27rem">
        {{ type }}
      </a-button>
    </a-form-model-item>
  </a-form-model>
</template>
<script>
import { mapActions } from "vuex";
import { handleLogin, handleRegister, refreshPage } from "@/utils/utils";
export default {
  name: "Form",
  props: ["type"],
  data() {
    return {
      formInline: {
        username: "",
        password: "",
        repassword: "",
      },
      rules: {
        username: [
          {
            required: true,
            message: "请输入用户名",
          },
        ],
        password: [
          {
            required: true,
            message: "请输入密码",
          },
        ],
        repassword: [
          {
            required: true,
            message: "请再次输入密码",
          },
          {
            validator: (rule, val, callback) => {
              // 自定义校验规则
              if (!val) {
                callback(new Error(""));
              } else if (val !== this.formInline.password) {
                callback(new Error("两次密码不一致"));
              } else {
                callback(); // 正确
              }
            },
            trigger: "change",
          },
        ],
      },
    };
  },
  methods: {
    handleSubmit(e) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 用户名和密码都不为空
          if (this.type === "登录") {
            // 登录
            handleLogin(this.formInline, this);
          } else {
            // 注册
            handleRegister(this.formInline, this);
          }
        } else {
          this.$message.error("请输入正确的格式");
        }
      });
    },
  },
};
</script>

